package other.edan.pass;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.rkhd.platform.sdk.ScheduleJob;
import com.rkhd.platform.sdk.data.model.Account;
import com.rkhd.platform.sdk.data.model.Department;
import com.rkhd.platform.sdk.data.model.User;
import com.rkhd.platform.sdk.exception.CustomConfigException;
import com.rkhd.platform.sdk.exception.ScriptBusinessException;
import com.rkhd.platform.sdk.exception.XsyHttpException;
import com.rkhd.platform.sdk.log.Logger;
import com.rkhd.platform.sdk.log.LoggerFactory;
import com.rkhd.platform.sdk.model.OperateResult;
import com.rkhd.platform.sdk.param.ScheduleJobParam;
import com.rkhd.platform.sdk.service.CustomConfigService;
import com.rkhd.platform.sdk.service.FutureTaskService;
import com.rkhd.platform.sdk.service.XoqlService;
import com.rkhd.platform.sdk.task.FutureTask;
import org.apache.commons.lang.StringUtils;
import other.edan.pass.utils.ComUtils;
import other.edan.pass.utils.DateTools;
import other.edan.pass.utils.HCXObjectService;

import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

/**
 * ClassName: UegularlyUpdatingUsersTask
 * Description: 定时更新国内营销用户信息
 * date: 2024/07/02
 *
 * @author fwm
 */
public class UegularlyUpdatingUsersTask implements ScheduleJob, FutureTask {
    // 信息配置
    private static Map<String, String> residentOfficeConfig;            //常驻办事处 配置信息
    private static final Logger LOGGER = LoggerFactory.getLogger();

    static {
        try {
            CustomConfigService instance = CustomConfigService.instance();
            residentOfficeConfig = instance.getConfigSet("ResidentOffice");
            if (residentOfficeConfig == null) {
                residentOfficeConfig = new HashMap<>();
            }
        } catch (CustomConfigException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void execute(ScheduleJobParam scheduleJobParam) {
        LOGGER.debug("定时更新国内营销部门/用户信息开始");
        try {
            String messageId = FutureTaskService.instance().addFutureTask(UegularlyUpdatingUsersTask.class, null);
            LOGGER.info("messageId: " + messageId);
        } catch (Exception e) {
            LOGGER.error("定时更新用户信息异常, error:", e);
        }
        LOGGER.debug("定时更新用户信息结束");
    }

    @Override
    public void execute(String s) throws ScriptBusinessException {
        LOGGER.debug("定时更新国内营销部门/用户信息开始");

        try {
            updateResidentOffice();

            updateDepartment();

            dealUserManagerId();
        } catch (Exception e) {
            LOGGER.error("更新部门/用户信息发生异常:"+e.getMessage());
        }
    }

    //更新国内营销部门负责人、大区总监、办事处主任、办事处助理
    private void updateDepartment(){
        Long twoDaysBefore = DateTools.getDaysBeforeLong(2);
        String sql = "select id, parentDepartId,departName, thirdDepartName, informationForm__c,departCode from department " +
                " where (informationForm__c=1) and (departCode is not null) ";// where (updatedAt >=" + twoDaysBefore + ")";
        List<Department> departmentList = HCXObjectService.queryAll(sql);
        if(departmentList.isEmpty()) {
            LOGGER.info("没有符合条件的部门信息");
            return;
        }

        LOGGER.info("查询到的部门数量:"+departmentList.size());

        sql="select id, name, employeeCode,residentOffice__c from user where informationForm__c=1";
        List<User> userList=HCXObjectService.queryAll(sql);
        if(userList.size()<=0) {
            LOGGER.info("查询到用户信息");
            return;
        }

        LOGGER.info("查询到的用户数量:"+userList.size());

        Map<String,Long> userMap=new HashMap<>();               //用工工号，用户ID
        Map<Long,Long> officeAssistantMap=new HashMap<>();      //常驻办事处，办事处助理ID（用户ID）

        for(User user:userList){
            userMap.put(user.getEmployeeCode(),user.getId());
            if(null!=user.getResidentOffice__c()){
                officeAssistantMap.put(user.getResidentOffice__c(),user.getId());
            }
        }
        LOGGER.info("常驻办事处，对应的办事处助理:"+officeAssistantMap.toString());

        //部门负责人
        Map<Long,Long> departmentOwnerMap=new HashMap<>();              //部门ID，部门负责人ID
        for (Department department : departmentList) {
            String thirdDepartName = department.getThirdDepartName();                   //部门负责人
            Long userId=userMap.get(thirdDepartName);
            if(null==userId){
                LOGGER.info("该工号【"+thirdDepartName+"]没有找到对应用户。");
                continue;
            }
            departmentOwnerMap.put(department.getId(),userId);
        }
        LOGGER.info("部门对应的负责人:");

        //大区总监
        Map<String,Long> fourthRegionalDirectorMap=new HashMap<>();             //部门编码，大区总监ID(四级）
        for(Department department:departmentList){
            if(department.getParentDepartId().equals(3351254149388908L)){                   //销售线下级部门
                fourthRegionalDirectorMap.put(department.getDepartCode(),departmentOwnerMap.get(department.getId()));
            }
        }
        LOGGER.info("大区总监:"+fourthRegionalDirectorMap.toString());

        Map<Long,Long> regionalDirectorMap=new HashMap<>();             //部门ID，大区总监ID
        for(Department department:departmentList){
            if(department.getDepartCode().startsWith("001003")){                   //销售线下级部门
                String departCode=department.getDepartCode();
                for(Map.Entry<String,Long> entry:fourthRegionalDirectorMap.entrySet()){
                    //如果是第四级的部门编码开头的，则用第四级的负责人作为大区总监
                    String  key=entry.getKey();
                    if(departCode.startsWith(key)){
                        regionalDirectorMap.put(department.getId(),entry.getValue());
                    }
                }
            }
        }

        //办事处主任
        Map<Long,Long> directorOfficeMap=new HashMap<>();               //部门ID，办事处主任
        for(Department department:departmentList){
            String departName=department.getDepartName();
            if(department.getDepartCode().startsWith("001003") && (departName.endsWith("办")|| (departName.endsWith("处") || (departName.endsWith("分公司"))))){
                    directorOfficeMap.put(department.getId(),departmentOwnerMap.get(department.getId()));
            }
        }
        LOGGER.info("办事处主任："+directorOfficeMap.toString());

        List<Department>  updateDeptList = new ArrayList<>();
        for(Department department:departmentList){
            Department updateDept=new Department();
            updateDept.setId(department.getId());
            updateDept.setDeptOwnerNew__c(departmentOwnerMap.get(department.getId()));              //部门负责人
            updateDept.setRegionalDirector__c(regionalDirectorMap.get(department.getId()));         //大区总监
            updateDept.setDepartmentOwner__c(directorOfficeMap.get(department.getId()));            //办事处主任
            updateDept.setOfficeAssistant__c(officeAssistantMap.get(department.getId()));           //办事处助理
            updateDeptList.add(updateDept);
        }

        //TEST
        /*for(Department department:updateDeptList){
            HCXObjectService.update(department);
        }*/
        //END TEST

        LOGGER.info("更新的部门数量:"+departmentList.size());
        if(departmentList.size()>0){
            HCXObjectService.updateBatch(departmentList);
        }
    }

    //更新用户的直线上级和虚线上级
    private void updateUsers() {
        try {
            //获取所有用户
            String sql = "Select id,employeeCode from user where informationForm__c = 1";
            List<User> allUserList = HCXObjectService.queryAll(sql);
            Map<String, Long> userEmployCodeMap = new HashMap<>();
            for (User user : allUserList) {
                if (null != user.getEmployeeCode()) {
                    userEmployCodeMap.put(user.getEmployeeCode(), user.getId());
                }
            }
            LOGGER.info(userEmployCodeMap.toString());

            //获取两天来更新的用户
            Long twoDaysBefore = DateTools.getDaysBeforeLong(2);
            sql = "select id,expertise,hobby,name from user where informationForm__c=1 and updatedAt >=" + twoDaysBefore;
            List<User> userList = HCXObjectService.queryAll(sql);

            List<User> updateUserList = new ArrayList<>();
            for (User user : userList) {
                User updateUser = new User();
                updateUser.setId(user.getId());
                updateUser.setName(user.getName());
                String reportingToCode = user.getExpertise();     //直接上级
                String virtualCode = user.getHobby();             //虚线上级

                Long reportingTo = userEmployCodeMap.get(reportingToCode);
                Long virtual = userEmployCodeMap.get(virtualCode);

                updateUser.setManagerId(reportingTo);
                updateUser.setVirtualSuperior__c(virtual);

                updateUserList.add(updateUser);
            }

            LOGGER.info("更新用户数量:" + updateUserList.size());
            if (updateUserList.size() > 0) {
                HCXObjectService.updateBatch(updateUserList);
            }
        } catch (Exception e) {
            LOGGER.error("定时更新用户信息异常, error:", e);
        }
    }


    // 更新用户的直线上级和虚线上级
    private void dealUserManagerId() {
        try {
            LOGGER.info("更新用户的直线上级和虚线上级 ==> 开始处理");

            // 获取所有用户
            String sql = "select id,name,employeeCode,expertise,managerId,hobby,virtualSuperior__c from user where informationForm__c = 1 and employeeCode is not null";
            List<JSONObject> userList = XoqlService.instance().query(sql).getRecords();
            Map<String, Long> crmUserMap = userList.stream().collect(Collectors.toMap(e -> e.getString("employeeCode"), e1 -> e1.getLong("id"), (e, e1) -> e));
            LOGGER.info("crmUserMap:" + crmUserMap.size());

            // 获取直接上级
            List<User> updateUserList = new ArrayList<>();
            for (JSONObject user : userList) {

                // 直属上级
                String expertise = user.getString("expertise");
                Long newManagerId = crmUserMap.get(expertise);
                Long managerId = user.getLong("managerId");

                // 虚拟上级
                String hobby = user.getString("hobby");
                Long newVirtualSuperiorId = crmUserMap.get(hobby);
                Long virtualSuperiorId = user.getLong("virtualSuperior__c");

                // 判断是否需要更新
                if (Objects.equals(newManagerId, managerId) && Objects.equals(newVirtualSuperiorId, virtualSuperiorId)) {
                    continue;
                }

                // 修改
                User upUser = new User();
                upUser.setId(user.getLong("id"));
                upUser.setManagerId(newManagerId);
                upUser.setVirtualSuperior__c(newVirtualSuperiorId);
                updateUserList.add(upUser);
                if (updateUserList.size() > 100) {
                    HCXObjectService.updateBatch(updateUserList);
                    updateUserList.clear();
                }
            }

            LOGGER.info("更新用户:" + updateUserList);
            if (updateUserList.size() > 0) {
                HCXObjectService.updateBatch(updateUserList);
            }

            LOGGER.info("更新用户的直线上级和虚线上级 处理完成");
        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.error("定时更新用户信息异常, error:", e);
        }
    }

    //更新用户常驻办事处
    private void updateResidentOffice() {
        Long twoDaysBefore = DateTools.getDaysBeforeLong(2);
        String deptCode = residentOfficeConfig.get("ResidentOfficeDept");
        String sql = "select id,name,im,departmentCode__c,parentDept__c from user  " +
                " where (im is not null) and (informationForm__c=1) and (departmentCode__c=" + deptCode + ") and (updatedAt >=" + twoDaysBefore + ")";
        List<User> userList = HCXObjectService.queryAll(sql);
        if (userList.size() <= 0) {
            LOGGER.info("没有需要更新的用户信息");
            return;
        }

        LOGGER.info("用户数量:" + userList.size());

        List<User> updateUserList = new ArrayList<>();

        for (User user : userList) {
            String im = user.getIm().substring(0, 2);

            User newUser = new User();
            newUser.setId(user.getId());

            if (im.equals("长沙")) {
                String changSaId = residentOfficeConfig.get("Changsha");
                newUser.setResidentOffice__c(Long.parseLong(changSaId));
                updateUserList.add(newUser);
                continue;
            }

            sql = "select id,departCode,departName from department where (informationForm__c=1) and  departName like '" + im + "%'";
            List<Department> departmentList = HCXObjectService.queryAll(sql);
            if (departmentList.size() >= 2) {
                LOGGER.info("常驻办事处大于2");
                continue;
            }

            newUser.setResidentOffice__c(departmentList.get(0).getId());
            updateUserList.add(newUser);
        }

        LOGGER.info("更新的用户数量：" + updateUserList.size());
        if (updateUserList.size() > 0) {
            HCXObjectService.updateBatch(updateUserList);
        }
    }

    private void updateDepartment2() {
        Long twoDaysBefore = DateTools.getDaysBeforeLong(2);
        String sql = "select id, parentDepartId,departName, thirdDepartName, informationForm__c,departCode from department " +
                " where informationForm__c=1 and departCode is null";// where (updatedAt >=" + twoDaysBefore + ")";
        List<Department> departmentList = HCXObjectService.queryAll(sql);
        if (departmentList.isEmpty()) {
            LOGGER.info("没有符合条件的部门信息");
            return;
        }

        System.err.println(departmentList);
    }

    public static void main(String[] args) throws IOException, XsyHttpException {
        UegularlyUpdatingUsersTask api=new UegularlyUpdatingUsersTask();
        //api.updateDepartment();

        //api.dealUserManagerId();

        /*Department department=new Department();
        department.setId(3351175171955279L);
        department=HCXObjectService.get(department);
        System.err.println(department);
         */

        //3351254149388908L：销售线  部门负责人：000031
        //3351254505200281：超声线   部门负责人：008550
        //3351254505200301：超声线市场   部门负责人：008350
        //3351255327693390：区域市场   部门负责人：008350
        //3351255830501954：南区   部门负责人：008350
        //3351255830501958：北区   部门负责人：008350


        /*Department department = new Department();
        department.setId(3351255830501958L);
        department=HCXObjectService.get(department);
        System.err.println(department.getThirdDepartName());*/
    }
}